package com.pro.framework.spring.util;

import com.pro.framework.api.IReloadService;
import com.pro.framework.api.model.FrameworkException;
import com.pro.framework.api.model.IModel;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public abstract class BaseEntityFactory<KEY, ENTITY extends IModel> implements IReloadService {

    private final Map<KEY, ENTITY> entityMap = new ConcurrentHashMap<>();

    public ENTITY get(KEY key) {
        ENTITY entity = entityMap.get(key);
        if (entity == null) {
            throw new FrameworkException("未找到键对应的实体__", key, getClass());
        }
        return entity;
    }

    @Override
    @PostConstruct
    public void reload() {
        entityMap.clear();
        entityMap.putAll(getEntityMap());
    }

    protected abstract Map<KEY, ENTITY> getEntityMap();
}
